package zzk.gwxer.tttttt.hanlan.ding.ui.component

import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import zzk.gwxer.tttttt.hanlan.ding.MainActivity
import zzk.gwxer.tttttt.hanlan.ding.ui.theme.DingTheme
import zzk.gwxer.tttttt.hanlan.ding.vm.MainViewModel

@Composable
fun CountdownTimer(viewModel: MainViewModel) {
    val remainingTime = viewModel.remainingTime.collectAsState()
    val isCountingDown = viewModel.isTimerOn.collectAsState()

    LaunchedEffect(isCountingDown.value) {
        if (isCountingDown.value) {
            while (remainingTime.value > 1) {
                if (!isCountingDown.value) break
                delay(1000)
                viewModel.timerContinueOneSecond()
            }
            viewModel.updateTimerState(false)
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Text(text = "${remainingTime.value}s", fontSize = 60.sp)
    }
}


@Preview(showBackground = true)
@Composable
fun CountDownTimerPreview() {
    DingTheme {

    }
}